package com.lishuang.controller;

import com.lishuang.DAO.visitLogDAO.visitLog;
import com.lishuang.domain.json.Device;
import com.lishuang.manager.DeviceScheduler;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiShuang
 * @version 1.0.0
 * @date 2022/11/11 10:29
 */
@RestController
@CrossOrigin(origins = {"*","null"})
public class Controller {
    private DeviceScheduler deviceScheduler = new DeviceScheduler();

    public Controller(){
        //先暂时提交20个任务
        for (int i = 0; i < 5; i++) {
            Device device = new Device(true);
            invoke(device);
        }
    }

    /**
     * 仅限演示功能！
     */
    @GetMapping("/device/demo")
    public List<visitLog> demoShow() throws Exception {
        return deviceScheduler.demo();
    }

    /**
     * <key>UUID</key>
     * <value>Device</value>
     * @return
     */
    //获得当前网关接入设备的状态
    @ResponseBody
    @PostMapping("/device/index")
    public Map<String, Device> home(){
        return DeviceScheduler.map;
    }

    //提交一个任务
    @PostMapping("/device/invoke")
    public Object invoke(@RequestBody Device device){
        Map<String, Object> map = new HashMap<>();
        try{
            deviceScheduler.startDeviceThread(device);
            map.put("message","success");
            map.put("UUID",device.getUuid());
            map.put("deviceID",device.getDeviceId());
        }catch (Exception e){
            map.put("message","failed");
            map.put("deviceID",device.getDeviceId());
            e.printStackTrace();
        }
        return map;
    }

    //停止某个设备
    @ResponseBody
    @PostMapping("/device/stop")
    public Map<String,Object> stop(@RequestBody String uuid){
        Map<String, Object> map = new HashMap<>();
        try {
            deviceScheduler.stopDeviceThread(uuid);
            map.put("message","success");
        }catch(Exception e){
            map.put("message","failed");
        }
        return map;
    }

    //删除某个设备
    @PostMapping("/device/delete")
    public Map<String,Object> delete(@RequestBody String uuid){
        Map<String, Object> map = new HashMap<>();
        try{
            deviceScheduler.deleteDeviceThread(uuid);
            map.put("message","success");
        }catch (Exception e){
            map.put("message","failed");
        }
        return map;
    }
    //修改设备
    @PostMapping("/device/modify")
    public Map<String,Object> modify(@RequestBody Device device){
        Map<String, Object> map = new HashMap<>();
        Device device1 = deviceScheduler.getMap().get(device.getUuid());
        if(device1==null)
            map.put("message","failed");
        device1.modify(device);
        map.put("message","success");
        return map;
    }
}

